package cn.itcast.service;

import cn.itcast.pojo.Permission;
import cn.itcast.pojo.Role;
import cn.itcast.pojo.User;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        User user = userService.findByUsername(name);
        if (user == null) {
            return null;
        }
        //创建存储角色和权限的list集合
        List<GrantedAuthority> list = new ArrayList<>();
        //获取用户的角色信息
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            //添加用户角色信息
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                //添加权限信息
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        //授予权限  三个参数 用户名 用户密码(如果没有加密，需要在前面加上{noop}) 存储角色和权限的list集合
        org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(name,user.getPassword(),list);

        return securityUser;
    }
}
